package top.rainbowecho.common.standard.database.manager.impl;

import top.rainbowecho.common.standard.database.DatabaseHelper;
import top.rainbowecho.common.standard.database.manager.DatabaseManager;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 杨健
 * @since 2019/8/23 10:09
 */
public class DatabaseManagerImpl implements DatabaseManager {
    private DatabaseHelper databaseHelper = new DatabaseHelper();

    @Override
    public List<String> selectAllTables(String database) {
        String sql = String.format("show tables from `%s`", database);
        return databaseHelper.selectSingleColumn(sql, resultSet -> {
            try {
                return resultSet.getString(1);
            } catch (SQLException e) {
                return null;
            }
        });
    }

    @Override
    public List<String> selectTableFields(String tableName) {
        String sql = String.format("SELECT\n" +
                "\tcolumn_name columnName,\n" +
                "\tdata_type dataType,\n" +
                "\tcolumn_comment columnComment,\n" +
                "\tcolumn_key columnKey,\n" +
                "\textra\n" +
                "FROM\n" +
                "\tinformation_schema.`COLUMNS`\n" +
                "WHERE\n" +
                " table_schema =(SELECT DATABASE())\n" +
                " AND table_name = '%s';", tableName);

        return databaseHelper.selectSingleColumn(sql, resultSet -> {
            try {
                return resultSet.getString("columnName");
            } catch (SQLException e) {
                return null;
            }
        });
    }


}
